import sys
from enum import Enum
from os.path import abspath, join, dirname

ROOT_DIR = abspath(join(dirname(abspath(__file__)), '../../'))
if ROOT_DIR not in sys.path:
    sys.path.append(ROOT_DIR)

from app.service.upload import q_box
from app.service.sms import sms_box, sms_template
import datetime
import json
from app.settings.config import MYSQL_USER, MYSQL_PASSWORD, MYSQL_HOST, MYSQL_DB, MYSQL_PORT

from app.service.format_datetime import format_datetime, format_datetime_group
from app.service.comment import media_root_comments, get_comment_object_first_comment
from app.service.menu import new_menu, nav_name
from app.service.search import init_all_mapping, index_my_media, search_my_media, index_home_media, search_home_media
from main import app

from app.db.search import es_init, es

from app.lib.txt import path_str_arr
from app.model import mysql
from app.service.folder import new_folder, get_folders, get_user_root_folder_ids, reset_folder_covers, \
    reset_folder_and_parent_covers
from tortoise import Tortoise, run_async
from app.model.mysql import Folder
from tortoise.query_utils import Q


async def run():
    """"""
    await Tortoise.init(db_url=f'mysql://{MYSQL_USER}:{MYSQL_PASSWORD}@{MYSQL_HOST}:{MYSQL_PORT}/{MYSQL_DB}', modules={"models": ["app.model.mysql"]})
    await Tortoise.generate_schemas()
    es_init()


async def close_run():
    """"""
    await Tortoise.close_connections()


async def init_menus():
    """"""
    menu_path = join(ROOT_DIR, 'app/scripts/data/menus.json')
    with open(menu_path, 'r') as f:
        menus = json.loads(f.read())
    for a in menus:
        a_name = a.get('name', '')
        a_children = a.get('children', [])
        a_m = await new_menu(a_name)
        for b in a_children:
            b_name = b.get('name', '')
            b_children = b.get('children', [])
            b_m = await new_menu(b_name, parent_id=a_m.id)
            for c in b_children:
                c_name = c.get('name', '')
                c_children = c.get('children', [])
                c_m = await new_menu(c_name, parent_id=b_m.id)
                for d in c_children:
                    d_name = d.get('name', '')
                    d_children = d.get('children', [])
                    d_m = await new_menu(d_name, parent_id=c_m.id)
                    for e in d_children:
                        e_name = e.get('name', '')
                        e_m = await new_menu(e_name, parent_id=d_m.id)


async def index_my_medias():
    """"""
    my_medias = await mysql.MyMedia.filter()
    for my_media in my_medias:
        await index_my_media(my_media.user_id, my_media.media_id)


async def index_home_medias():
    """"""
    media_ids = await mysql.Media.filter().values_list('id', flat=True)
    for media_id in media_ids:
        await index_home_media(media_id)


async def delete_indexs():
    """"""
    indexs = ['designer_my_media', 'designer_home']
    for index in indexs:
        has_index = await es.indices.exists(index)
        if has_index:
            await es.indices.delete(index)


async def main():
    """"""
    await run()

    # await init_menus()

    await delete_indexs()
    await init_all_mapping()
    await index_my_medias()
    await index_home_medias()
    # await search_home_media({
    #     "offset": 0,
    #     "limit": 10,
    #     "keyword": "欧式",
    #     "must_tags": [],
    #     "should_tags": [
    #
    #     ],
    #     "media_type": 0,
    #     "whole_case": False,
    # })
    # token = 'Sw9cBvAZ42ZAsfkKNFbhIvOEncnEBnJcs4y94-OA:gWPO0PMBmVgJSHlRqqZHGYSZbpc=:eyJzY29wZSI6ImRvbWUtbWVkaWEiLCJkZWFkbGluZSI6MTU5NjA3NzAxNywicmV0dXJuQm9keSI6IntcImtleVwiOiAkKGtleSksIFwic2l6ZVwiOiAkKGZzaXplKSwgXCJ0eXBlXCI6ICQobWltZVR5cGUpLCBcImhhc2hcIjogJChldGFnKSwgXCJ3aWR0aFwiOiAkKGltYWdlSW5mby53aWR0aCksIFwiaGVpZ2h0XCI6ICQoaW1hZ2VJbmZvLmhlaWdodCksIFwib3JpZW50YXRpb25cIjogJChpbWFnZUluZm8ub3JpZW50YXRpb24pLCBcImNvbG9yXCI6ICQoZXhpZi5Db2xvclNwYWNlLnZhbCksIFwidmlkZW9EdXJhdGlvblwiOiAkKGF2aW5mby52aWRlby5kdXJhdGlvbiksIFwidmlkZW9XaWR0aFwiOiAkKGF2aW5mby52aWRlby53aWR0aCksIFwidmlkZW9IZWlnaHRcIjogJChhdmluZm8udmlkZW8uaGVpZ2h0KSwgXCJ2aWRlb1JvdGF0ZVwiOiAkKGF2aW5mby52aWRlby50YWdzLnJvdGF0ZSksIFwidXJsXCI6IFwiaHR0cDovL21lZGlhLnpjMDkwMS5jb20vJChrZXkpP2ltYWdlVmlldzIvMS93LzMwMC9oLzMwMFwiLCBcIm9yaWdpbmFsVXJsXCI6IFwiaHR0cDovL21lZGlhLnpjMDkwMS5jb20vJChrZXkpXCJ9IiwicmV0dXJuVXJsIjpudWxsLCJzYXZlS2V5IjoibmVzdGNpYW8vJChldGFnKSJ9'
    # file_path = '/Users/xqk/Desktop/abc.png'
    # info = q_box.qiniu_upload_file(token, None, file_path=file_path)
    # # print(info)
    # print(json.dumps(info[0], ensure_ascii=False, indent=True))

    await close_run()


if __name__ == "__main__":

    run_async(main())
    pass
